package com.moregold.mvvmlib.ext

import com.google.gson.JsonObject
import com.moregold.mvvmlib.entity.BaseResult
import com.moregold.mvvmlib.exception.AppException

/**
 * 处理返回值
 *
 * @param result 请求结果
 */

fun <T> VmLiveData<T>.paresVmResult(result: BaseResult<T>) {
    value = if (result.dataRight()) VmState.Success(result.data) else
        VmState.Error(AppException(result.getMessage()), result.status)
}

/**
 * 为了符合项目,直接用jsonObject数据的请求
 */
fun <T> VmLiveData<T>.paresVmResultForJsonObject(result: T) {
    if (result is JsonObject) {
        if ((result as JsonObject).has("status")) {
            if ((result as JsonObject).get("status").asInt == 0 || (result as JsonObject).get("status").asInt == 200) {
                value = VmState.Success(result)
            } else if ((result as JsonObject).has("msg")) {
                value = VmState.Error(
                    AppException((result as JsonObject).get("msg").asString),
                    (result as JsonObject).get("status").asInt
                )
            }
        } else if ((result as JsonObject).has("status") && (result as JsonObject).has("msg")) {
            value = VmState.Error(
                AppException((result as JsonObject).get("msg").asString),
                (result as JsonObject).get("status").asInt
            )
        }
    }
}

/**
 * 为了符合项目,直接用JsonArray数据的请求
 */
fun <T> VmLiveData<T>.paresVmResultForJsonArray(result: T) {
    value = VmState.Success(result)
}

/**
 * 异常转换异常处理
 */
fun <T> VmLiveData<T>.paresVmException(e: Throwable) {
    this.value = VmState.Error(AppException(e), -1)
}
